package com.jt.sp06zuul.filter;

import com.jt.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //过滤器类型 pre routing post error
    @Override
    public String filterType() {
        //return"pre"前置过滤器
        return FilterConstants.PRE_TYPE;
    }
    //过滤器的顺序号
    @Override
    public int filterOrder() {
        //有5个默认的过滤器,自己的过滤器加到末尾
        return 6;
    }
    //针对当前请求判断是否执行过滤代码
    //如果调用item-service,检查是否登陆,访问其他业务不检查,直接访问
    @Override
    public boolean shouldFilter() {

        //现获取当前请求的上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取当前请求服务调用的Id
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        //判断调用的是否为item-service
        return "item-service".equals(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //获得上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //获得request对象
        HttpServletRequest request = ctx.getRequest();
        //接收token参数
        String token = request.getParameter("token");
        //若没有token,阻止继续调用,直接返回响应
        if(StringUtils.isBlank(token)){
            //阻止继续调用
            ctx.setSendZuulResponse(false);

            //直接返回响应
            ctx.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            ctx.setResponseBody(JsonResult.err().code(400).msg("Not login! 未登录!").toString());
        }
        return null;
    }
}
